#
import matplotlib.pyplot as plt
import numpy as np
import pandas as pd
from pathlib import Path

# 设置全局字体
plt.rcParams['font.family'] = 'Times New Roman'  # 默认使用Times New Roman

#加载数据
def load_data():
    """从CSV文件加载数据"""
    data_file = Path("polar_chart_data.csv")

    return pd.read_csv(data_file)

# 自定义颜色方案（替换默认的C0,C1...）
CUSTOM_COLORS = {
    "A": "#b0d1a6",  # 浅绿
    "B": "#f5c5a0",  # 浅橙
    "C": "#e7a39a",  # 浅红
    "D": "#b1a5c9"   # 浅紫
}

def get_label_rotation(angle, offset):
    """计算文本标签的旋转角度和对齐方式"""
    rotation = np.rad2deg(angle + offset)
    if angle <= np.pi:
        alignment = "right"
        rotation = rotation + 180
    else:
        alignment = "left"
    return rotation, alignment


def add_labels(angles, values, labels, offset, ax):
    """添加文本标签到极坐标图"""
    padding = 4
    for angle, value, label in zip(angles, values, labels):
        angle = angle
        rotation, alignment = get_label_rotation(angle, offset)
        ax.text(x=angle, y=value + padding, s=label,
                ha=alignment, va="center",
                rotation=rotation, rotation_mode="anchor",
                fontsize=12,  # 字号设置为8
                color='#404040',  # 深灰色文字
                fontfamily='Times New Roman',  # 英文字体
                fontweight='normal',  # 正常粗细
                alpha=0.9  # 90%不透明度
                )


def create_polar_chart(df):
    """创建极坐标图"""
    # 计算角度和宽度
    ANGLES = np.linspace(0, 2 * np.pi, len(df), endpoint=False)
    VALUES = df["value"].values
    LABELS = df["name"].values
    WIDTH = 2 * np.pi / len(VALUES)
    OFFSET = np.pi / 2
    GROUP = df["group"].values

    # 分组设置
    PAD = 3
    ANGLES_N = len(VALUES) + PAD * len(np.unique(GROUP))
    ANGLES = np.linspace(0, 2 * np.pi, num=ANGLES_N, endpoint=False)
    WIDTH = (2 * np.pi) / len(ANGLES)

    # 计算索引
    GROUPS_SIZE = [len(i[1]) for i in df.groupby("group")]
    offset = 0
    IDXS = []
    for size in GROUPS_SIZE:
        IDXS += list(range(offset + PAD, offset + size + PAD))
        offset += size + PAD


    # 创建图表
    fig, ax = plt.subplots(figsize=(8, 8), subplot_kw={"projection": "polar"})

    ax.set_theta_offset(OFFSET)
    ax.set_ylim(-100, 100)
    ax.set_frame_on(False)
    ax.xaxis.grid(False)
    ax.yaxis.grid(False)
    ax.set_xticks([])
    ax.set_yticks([])

    # 使用自定义颜色
    COLORS = [CUSTOM_COLORS[g] for g in GROUP]

    # 绘制柱状图
    # 修改后的柱状图绘制代码
    bars = ax.bar(
        ANGLES[IDXS],
        VALUES,
        width=WIDTH,
        color=COLORS,
        edgecolor=COLORS,  # 边缘保持纯白不透明
        linewidth=2
    )

    # 如果需要单独控制每个柱子的透明度（可选）
    for bar, color in zip(bars, COLORS):
        bar.set_facecolor(color)  # 重新设置颜色（确保alpha生效）
        bar.set_alpha(0.5)  # 单独控制透明度

    add_labels(ANGLES[IDXS], VALUES, LABELS, OFFSET, ax)
    # 保存和显示
    plt.savefig('polar_chart.png', dpi=300, bbox_inches='tight')
    plt.show()


# ========== 主程序 ==========
if __name__ == "__main__":
    # 尝试加载数据，如果不存在则生成
    df = load_data()

    # 创建图表
    create_polar_chart(df)